<script setup>
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import {createFavorite, getThePostInfo, ListFavorites, toggleCollectPost, toggleLikePost} from "@/api/post/post.js";
import { ElMessage } from 'element-plus';
import {format} from "timeago.js";
import {Star, StarFilled} from "@element-plus/icons-vue";
import {throttle} from "lodash";
import PostComment from "@/components/PostComment.vue";

// 响应式数据
const route = useRoute();
const postInfo = ref(null);
const isCollected = ref(false);

// 获取帖子信息
onMounted( () => {
    const res = getThePostInfo(route.params.id, localStorage.getItem('account')).then((res) => {

      postInfo.value = res.data
      // 这里需要根据当前用户状态设置 isLiked 和 isCollected
    })
})


// 处理点赞
const handleLike = throttle(() => {
  // 调用点赞、取消点赞 API
  toggleLikePost(route.params.id, localStorage.getItem('account')).then((res) => {
    postInfo.value.isLiked = res.data
    if (res.data)  postInfo.value.likeNum++
    else postInfo.value.likeNum--
  })

}, 500)


// 处理收藏
const handleCollect = throttle((favoriteId) => {
  // 调用收藏、取消收藏 API
  toggleCollectPost(route.params.id, localStorage.getItem('account'), favoriteId).then((res) => {
    postInfo.value.isCollected = res.data;
    if (res.data == null) { /** do nothing */}
    else if (res.data)  postInfo.value.collectNum++
    else postInfo.value.collectNum--
  })
}, 500)






const collectDialogVisible = ref(false)
const favoriteList = ref([]) // 收藏夹列表
const newFavoriteName = ref('') // 新建收藏夹名称
const showCreateInput = ref(false) // 是否显示创建收藏夹输入框

// 打开收藏对话框
const openCollectMark = async () => {
  collectDialogVisible.value = true
  // 获取用户的收藏夹列表
  ListFavorites(localStorage.getItem('account'), route.params.id).then((res) => {
    favoriteList.value = res.data
  })
}

// 创建新收藏夹
const createNewFavorite = async () => {
  if (!newFavoriteName.value.trim()) {
    ElMessage.warning('请输入收藏夹名称')
    return
  }


  createFavorite(newFavoriteName.value, localStorage.getItem('account')).then((res) => {
    ElMessage.success('创建成功')
    showCreateInput.value = false
    newFavoriteName.value = ''
    // 刷新收藏夹列表
    ListFavorites(localStorage.getItem('account')).then((res) => {
      favoriteList.value = res.data
    })
  })

}


// 切换收藏状态
const toggleFavorite = async (item) => {
    const res = await toggleCollectPost(
        route.params.id,
        localStorage.getItem("account"),
        item.id
    )
    // 肯定是true的，不是true的都被return了
    item.isCollected = !item.isCollected

    if (res.data == null) {

    } else if (res.data) {
      postInfo.value.collectNum++
      postInfo.value.isCollected = true
    } else {
      postInfo.value.collectNum--
      postInfo.value.isCollected = false
    }
    item.isCollected ? item.count++ : item.count--;
    ElMessage.success(item.isCollected ? "收藏成功" : "取消收藏成功");


}
</script>

<template>
  <div v-loading="!postInfo" class="post-detail" v-if="postInfo">
    <!-- 帖子头部信息 -->
    <div class="post-header">
      <div class="user-info">
        <img :src="postInfo.avatar" class="avatar" :alt="postInfo.nickname">
        <div class="user-meta">
          <div class="nickname">{{ postInfo.isNameless ? '匿名用户' : postInfo.nickname }}</div>
          <div class="post-meta">
            <span class="time">{{  format(postInfo.createTime, 'zh_CN') }}</span>
            <span class="topic" v-if="postInfo.topicTitle">#{{ postInfo.topicTitle }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 帖子内容 -->
    <div class="post-content">
      <div class="content" v-html="postInfo.content"></div>
      <!-- 图片展示 -->
      <div class="image-list" v-if="postInfo.images && postInfo.images.length">
        <img v-for="(img, index) in postInfo.images"
             :key="index"
             :src="img.imageUrl"
             @click="previewImage(img.imageUrl)">
      </div>
    </div>

    <!-- 帖子底部操作栏 -->
    <div class="post-footer">
      <div class="action-item">
        <el-icon :size="22">
          <i v-if="!postInfo.isLiked" @click="handleLike" class="fa-regular fa-thumbs-up"></i>
          <i v-else @click="handleLike" style="color: #e96161" class="fa-solid fa-thumbs-up"></i>

        </el-icon>
        <span>{{ postInfo.likeNum }}</span>
      </div>
      <div class="action-item">
        <el-icon :size="22">
          <i class="fa-regular fa-comment-dots"></i>
        </el-icon>
        <span>{{ postInfo.commentNum }}</span>
      </div>
      <div class="action-item" @click="openCollectMark">
        <el-icon :size="23">
          <component :is="postInfo.isCollected ? StarFilled : Star"
                     :style="{ color: postInfo.isCollected ? '#FFD700' : '#666' }" />



        </el-icon>
        <span>{{ postInfo.collectNum }}</span>
      </div>
      <div class="action-item">
        <el-icon :size="22">
          <Share />
        </el-icon>
        <span>{{ postInfo.shareNum }}</span>
      </div>
    </div>

    <PostComment :post-id="route.params.id" :info="postInfo"></PostComment>
  </div>




  <el-dialog
      v-model="collectDialogVisible"
      title="添加收藏"
      width="400px"
      :close-on-click-modal="false"
      :show-close="true"
      destroy-on-close
  >
    <div class="collect-dialog-content">
      <!-- 收藏夹列表 -->
      <div class="favorite-list">
        <div
            v-for="item in favoriteList"
            :key="item.id"
            class="favorite-item"
        >
          <div class="favorite-info">
            <span class="favorite-name">{{ item.title }}</span>
            <span class="favorite-count">{{ item.count }} 个内容</span>
          </div>
          <el-button
              :type="item.isCollected ? 'info' : 'warning'"
              @click="toggleFavorite(item)"
          >
            {{ item.isCollected ? '已收藏' : '收藏' }}
          </el-button>
        </div>
      </div>

      <!-- 创建新收藏夹 -->
      <div v-if="showCreateInput" class="create-favorite">
        <el-input
            v-model="newFavoriteName"
            placeholder="请输入收藏夹名称"
            maxlength="20"
            show-word-limit
        >
          <template #append>
            <el-button @click="createNewFavorite">创建</el-button>
          </template>
        </el-input>
      </div>

      <div v-else class="create-favorite-btn" @click="showCreateInput = true">
        <i class="el-icon-plus"></i>
        <span>新建收藏夹</span>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="collectDialogVisible = false;showCreateInput = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
.post-detail {
  max-width: 850px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.post-header {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.user-meta {
  flex: 1;
}

.nickname {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.post-meta {
  font-size: 14px;
  color: #999;
  margin-top: 4px;
}

.topic {
  margin-left: 12px;
  color: #1890ff;
}

.post-content {
  margin-bottom: 20px;
}

.content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
}

.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 8px;
  margin-top: 16px;
}

.image-list img {
  width: 100%;
  border-radius: 4px;
  cursor: pointer;
}

.post-footer {
  display: flex;
  justify-content: space-around;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  color: #666;
  padding: 8px 16px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.action-item:hover {
  background-color: #f5f5f5;
}

.action-item:has(.el-icon:first-child) .thumb-up-filled {
  color: #ff6b6b;
}

.action-item:has(.el-icon:first-child) .star-filled {
  color: #ffd43b;
}

.action-item:has(.chat-dots) {
  color: #4dabf7;
}

.action-item:has(.share) {
  color: #51cf66;
}

.el-icon {
  font-size: 20px;
}

.action-item span {
  font-size: 14px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #999;
}
.collect-dialog-content {
  min-height: 300px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.favorite-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.favorite-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.favorite-item:hover {
  background-color: #f5f5f5;
}

.favorite-item.active {
  background-color: #e6f4ff;
}

.favorite-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.favorite-name {
  font-size: 14px;
  color: #333;
}

.favorite-count {
  font-size: 12px;
  color: #999;
}

.create-favorite {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

.create-favorite-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  color: #1890ff;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.create-favorite-btn:hover {
  background-color: #f0f7ff;
}

.dialog-footer {
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
}
</style>
